<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;
use User\Api\UserApi;

/**
 * 后台用户控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class UserController extends AdminController {

    /**
     * 用户管理首页
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function index(){ 
        $nickname           = I('nickname');
        $map['type']        = I('type',1) ; # 默认筛选出来的为注册用户
        $map['status']      =   array('egt',0); # 0为禁用 -1 为删除 
        if(is_numeric($nickname)){
            //$map['uid|nickname']=   array(intval($nickname),array('like','%'.$nickname.'%'),'_multi'=>true);
            $map['mobile']      =   array('like','%'.$nickname.'%') ;
        }else{
            $map['nickname']    =   array('like', '%'.(string)$nickname.'%');
        }
        $list   = $this->lists('Member', $map);  
        int_to_string($list);
        $this->assign('_list', $list);
        $this->meta_title = '用户信息';
        $this->display();
    }

    /**
     * Ajax接口调用 根据字符串 手机号 或者 用户名 匹配用户 进行返回 
     * @return [type] [description]
     */
    public function getUserByCheck($keywords=''){
        if ( $keywords ==' ')  $this->error('无效的筛选');
        $map = array();
        if ( is_numeric($keywords) ) {
            # 手机号查
            $map['mobile'] = $keywords ; 
        }else{
            $map['nickname'] = $keywords ; 
        }
        $info = M('member')->where($map)->find();
        if ( $info ) {
            $this->success($info) ; 
        }else{
            $this->error('未查找到匹配用户');
        }
    }
    /**
     * 模块管理员 
     */
    public function sysmember(){
        $nickname       = I('nickname');
        $map['type']    = 10 ; # type 10 代表为模块管理员账户 
        $map['status']  =   array('egt',0); # 0为禁用 -1 为删除 
        if( isset($_GET['nickname']) ){
           $map['nickname']    =   array('like', '%'.(string)$nickname.'%')  ;
        } 
        $list   = $this->lists('Member', $map);  
        int_to_string($list);
        $this->assign('_list', $list);
        $this->meta_title = '模块管理员 信息';  
        # 获取用户组列表 
        $group_list = M('auth_group')->order("id ASC")->select();
        $this->assign('group_list',$group_list) ;  
        $this->display();
    } 
     /**
     * 用户仓库 
     */
    public function mdata(){ 
        $map['status']  =  1 ;   
        $truename = I('truename') ;
        if( $truename!= '' ){
            if(is_numeric($truename)){ 
                $map['mobile']      =   array('like','%'.$truename.'%') ;
            }else{
                $map['truename']    =   array('like', '%'.(string)$truename.'%');
            } 
        } 
        $list   = $this->lists('member_data', $map);   
        $this->assign('_list', $list);
        $this->meta_title = '用户仓库管理';   
        $this->display();
    }
    /**
     * 修改昵称初始化
     * @author huajie <banhuajie@163.com>
     */
    public function updateNickname(){
        $nickname = M('Member')->getFieldByUid(UID, 'nickname');
        $this->assign('nickname', $nickname);
        $this->meta_title = '修改昵称';
        $this->display('updatenickname');
    }

    /**
     * 修改昵称提交
     * @author huajie <banhuajie@163.com>
     */
    public function submitNickname(){
        //获取参数
        $nickname = I('post.nickname');
        $password = I('post.password');
        empty($nickname) && $this->error('请输入昵称');
        empty($password) && $this->error('请输入密码');
        //密码验证
        $User   =   new UserApi();
        $uid    =   $User->login(UID, $password, 4);
        ($uid == -2) && $this->error('密码不正确');

        $Member =   D('Member');
        $data   =   $Member->create(array('nickname'=>$nickname));
        if(!$data){
            $this->error($Member->getError());
        }
        $res = $Member->where(array('uid'=>$uid))->save($data);
        if($res){
            $user               =   session('user_auth');
            $user['username']   =   $data['nickname'];
            session('user_auth', $user);
            session('user_auth_sign', data_auth_sign($user));
            $this->success('修改昵称成功！');
        }else{
            $this->error('修改昵称失败！');
        }
    }

    /**
     * 修改密码初始化
     * @author huajie <banhuajie@163.com>
     */
    public function updatePassword(){
        $this->meta_title = '修改密码';
        $this->display('updatepassword');
    }

    /**
     * 修改密码提交
     * @author huajie <banhuajie@163.com>
     */
    public function submitPassword(){
        //获取参数
        $password   =   I('post.old');
        empty($password) && $this->error('请输入原密码');
        $data['password'] = I('post.password');
        empty($data['password']) && $this->error('请输入新密码');
        $repassword = I('post.repassword');
        empty($repassword) && $this->error('请输入确认密码');

        if($data['password'] !== $repassword){
            $this->error('您输入的新密码与确认密码不一致');
        }

        $Api    =   new UserApi();
        $res    =   $Api->updateInfo(UID, $password, $data);
        if($res['status']){
            $this->success('修改密码成功！');
        }else{
            $this->error($res['info']);
        }
    }


     /**
     * 用户信息编辑
     * @author changziming <294207330@qq.com>
     */
    public function edit($uid = 0){
        if(IS_POST){ 
            if($_POST["uid"]){ 
                $data = $_POST ;  
                unset($data['uid']) ; 
                $result = M('member')->where("uid='$uid'")->save($data); 
                if($result!==false){  
                    $this->success('更新成功') ;
                } else {
                    $this->error('更新失败55'.$id);
                }
            } else {
                $this->error(M()->getError());
            }
        } else {
            $info = array();
            $info = M('member')->find($uid);  
            if($info['dang_zid'] > 0 ){ 
                // 获取该党支部下的所有党小组 
                $dangG = M('dang_zu')->where(array('dang_zid'=>$info['dang_zid'] ) )->order('sort ASC')->select();
                $this->assign('dangG',$dangG);  
            }
            $this->assign('info',$info); 
            $this->meta_title = '编辑用户';
            $this->display();
        }
    }

    /**
     * 用户行为列表
     * @author huajie <banhuajie@163.com>
     */
    public function action(){
        //获取列表数据
        $Action =   M('Action')->where(array('status'=>array('gt',-1)));
        $list   =   $this->lists($Action);
        int_to_string($list);
        // 记录当前列表页的cookie
        Cookie('__forward__',$_SERVER['REQUEST_URI']);

        $this->assign('_list', $list);
        $this->meta_title = '用户行为';
        $this->display();
    }

    /**
     * 新增行为
     * @author huajie <banhuajie@163.com>
     */
    public function addAction(){
        $this->meta_title = '新增行为';
        $this->assign('data',null);
        $this->display('editaction');
    }

    /**
     * 编辑行为
     * @author huajie <banhuajie@163.com>
     */
    public function editAction(){
        $id = I('get.id');
        empty($id) && $this->error('参数不能为空！');
        $data = M('Action')->field(true)->find($id);

        $this->assign('data',$data);
        $this->meta_title = '编辑行为';
        $this->display('editaction');
    }

    /**
     * 更新行为
     * @author huajie <banhuajie@163.com>
     */
    public function saveAction(){
        $res = D('Action')->update();
        if(!$res){
            $this->error(D('Action')->getError());
        }else{
            $this->success($res['id']?'更新成功！':'新增成功！', Cookie('__forward__'));
        }
    }

    /**
     * 系统管理员的删除 
     * 直接删除好了 
     */
    public function sysmemberdel(){
        $id = array_unique((array)I('id',0));
        if( in_array(C('USER_ADMINISTRATOR'), $id)){
            $this->error("不允许对超级管理员执行该操作!");
        }
        $id = is_array($id) ? implode(',',$id) : $id;
        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        $map['uid']  = array('in',$id);
        $map['type'] = 10 ;
        M('Member')->where($map)->delete();
        # 删除登录表 
        M('ucenter_member')->where( array('id'=>array('in',$id) ) )->delete(); 
        # 删除用户角色表 
        M('auth_group_access')->where( array('uid'=>array('in',$id) ) )->delete();
        $this->success('删除成功！');
    }
    /**
     * 会员状态修改
     * @author 朱亚杰 <zhuyajie@topthink.net>
     */
    public function changeStatus($method=null){
        $id = array_unique((array)I('id',0));
        if( in_array(C('USER_ADMINISTRATOR'), $id)){
            $this->error("不允许对超级管理员执行该操作!");
        }
        $id = is_array($id) ? implode(',',$id) : $id;
        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        $map['uid'] =   array('in',$id);
        switch ( strtolower($method) ){
            case 'forbiduser':
                $this->forbid('Member', $map );
                break;
            case 'resumeuser':
                $this->resume('Member', $map );
                break;
            case 'deleteuser':
                $this->delete('Member', $map );
                break;
            default:
                $this->error('参数非法');
        }
    }
    /**
     * 这里修改后台的管理账户添加流程 $type = 10 代表为各模块管理账户
     * @param string $username   [description]
     * @param string $password   [description] 
     */
    public function add($username = '', $password = '', $repassword = '',  $mobile = '',$type="10"){
        if(IS_POST){
           if( $mobile == ''){
                $this->error('请输入手机号');
                exit() ; 
            }  
            /* 检测密码 */
            if($password != $repassword){
                $this->error('密码和重复密码不一致！');
            } 
            // 检测手机号是否存在 
            $isA = M('ucenter_member')->where(array('mobile'=>$mobile) )->count() ;
            if ( $isA > 0 ) {
                $this->error('该手机号已存在！');
                exit() ;
            }  
            //检查用户名是否存在 
            $isE = M('ucenter_member')->where( array('username'=>$username) )->count() ; 
            if ( $isE > 0 ) {
                $this->error('该用户名已存在！请更换');
                exit() ;
            }
            /* 调用注册接口注册用户 */
            $User   =   new UserApi;
            $uid    =   $User->register($username, $password,'', $mobile);
            if(0 < $uid){ //注册成功
                $user = array('uid' => $uid, 'nickname' => $username, 'status' => 1);
                $user['reg_time']   = time() ;  
                $user['type']       = $type ; # 后台添加管理账户的默认类别为10 
                $group_id           = I('group_id',0) ; # 用户组信息  
                if(!M('Member')->save($user)){
                    $this->error('用户添加失败！');
                } else {
                    # 这里设置用户组信息 
                    if ( $group_id > 0 ) {
                        # 先清除原有用户组 防止数据重复
                        M('auth_group_access')->where( array('uid'=>$uid) )->delete() ;
                        M('auth_group_access')->add( array('uid'=>$uid,'group_id'=>$group_id) ) ;
                    }
                    $this->success('用户添加成功！' ,U('sysmember') );
                }
            } else { //注册失败，显示错误信息
                $this->error($this->showRegError($uid));
            }
        } else {
            # 获取用户组列表 
            $group_list = M('auth_group')->order("id ASC")->select();
            $this->assign('group_list',$group_list) ;
            $this->meta_title = '新增用户';
            $this->display();
        }
    } 
    /**
     * 获取用户注册错误信息
     * @param  integer $code 错误编码
     * @return string        错误信息
     */
    private function showRegError($code = 0){
        switch ($code) {
            case -1:  $error = '用户名长度必须在16个字符以内！'; break;
            case -2:  $error = '用户名被禁止注册！'; break;
            case -3:  $error = '用户名被占用！'; break;
            case -4:  $error = '密码长度必须在6-30个字符之间！'; break;
            case -5:  $error = '邮箱格式不正确！'; break;
            case -6:  $error = '邮箱长度必须在1-32个字符之间！'; break;
            case -7:  $error = '邮箱被禁止注册！'; break;
            case -8:  $error = '邮箱被占用！'; break;
            case -9:  $error = '手机格式不正确！'; break;
            case -10: $error = '手机被禁止注册！'; break;
            case -11: $error = '手机号被占用！'; break;
            default:  $error = '未知错误';
        }
        return $error;
    }

}